package com.example.boot1;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号量
//抢车位   多个线程抢多个资源
// 6个车抢3个车位
public class SemaphoneDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);//模拟三个车位
        for (int i = 1; i <= 6 ; i++) {
            new Thread(() -> {
                try {
                    //抢占
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"\t 抢到车位了");
                    try{ TimeUnit.SECONDS.sleep(3);} catch(Exception e){e.printStackTrace();}
                    System.out.println(Thread.currentThread().getName()+"停车3秒后离开");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
